﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ECCSystem.DataAccess;
using ECCSystem.EntityClass;
//using Microsoft.Office.Core;
using Excel;
using ECCSystem.CheckClass;
using ECCSystem.UserControls;
using ECCSystem.BizRule;
using System.Xml;
using System.IO;
using ClsEmailTemplet = ECCSystem.BizRule.ClsEmailTemplet;
using ClsKindOfTemplet = ECCSystem.BizRule.ClsKindOfTemplet;

namespace ECCSystem
{

	public partial class frmTemplateImportAndInput : Form
	{
		object objMissing = System.Reflection.Missing.Value;
		int TreeMode = 0;
		int intRowAddIndex = 0;
		int intEditMode = 0;
		int intOldRowIndex = 0;
		int intCheckBoxMode = 3;
		int intValueChangeMode = 1;
		int intOpenMode = 0;
		public TreeNode objSelectNode = null;
		int objSelectNodeX = 0;
		int objSelectNodeY = 0;
		int Scollbar = 0;
        public frmEntryInput _frmEntryInput { get; set; }

	    public void EntryInputAction(Keys key)
        {
            if (_frmEntryInput != null)
                _frmEntryInput.EntryInputAction(key);

        }

	    public frmTemplateImportAndInput(int OpenMode)
		{
			intOpenMode = OpenMode;
			InitializeComponent();
		}

		#region "btnImport_Click"
		private void btnImport_Click(object sender, EventArgs e)
		{
			OpenFileDialog objFileDialog = new OpenFileDialog();
			//string strFileName = "";
			string strFilePath = "";

			objFileDialog.Title = "";
			objFileDialog.Multiselect = false;
			objFileDialog.AddExtension = true;
			objFileDialog.Filter = "Excel Worksheets|*.xls";
			objFileDialog.InitialDirectory = "C:\\";

			if (objFileDialog.ShowDialog(this) == DialogResult.OK)
			{
				strFilePath = objFileDialog.FileName;
				//strFileName = objFileDialog.SafeFileName;

				ClsExcel objClsExcel = new ClsExcel(strFilePath);

				string strFlg = objClsExcel.ReadExcel();
				if (strFlg == "")
				{
					MessageBox.Show("データ導入成功!", "ECC Information");
					this.tvClass.Nodes[0].Nodes.Clear();
					NodesBind(this.tvClass.Nodes[0]);
					tvClass.ExpandAll();
				}
				else if (strFlg == "1")
				{
					MessageBox.Show("データ導入失敗！","ECC Information");
				}
				else
				{
					MessageBox.Show(strFlg,"ECC Catch Error");
				}
			}


		}
		#endregion

		#region "tsmAdd_Click"

		private void tsmAdd_Click(object sender, EventArgs e)
		{

			tvClass.LabelEdit = true;

			TreeNode objSelect = new TreeNode();
			TreeNode objAdd = new TreeNode();

			if (this.tvClass.SelectedNode != null)
			{
				tvClass.LabelEdit = true;
				objSelect = this.tvClass.SelectedNode;
				//objSelect.BeginEdit();
				objAdd = objSelect.Nodes.Add("");
				objAdd.BeginEdit();
				objSelect.ExpandAll();
			}

			TreeMode = 1;
		}
		#endregion

		#region "tsmDel_Click"
		private void tsmDel_Click(object sender, EventArgs e)
		{
			TreeNode objSelect = new TreeNode();
			TreeNode objSelectTmp = new TreeNode();
			objSelect = this.tvClass.SelectedNode;
			int intNodeIndex = objSelect.Index;
			ArrayList objArr = new ArrayList();;

			if (objSelect.Nodes.Count > 0)
			{
				if (MessageBox.Show("全てのサブノードを削除しますか？", "ECC Information", MessageBoxButtons.YesNo) == DialogResult.Yes)
				{
					if (EnumerateNode(objSelect, objArr) == false)
					{
						MessageBox.Show("全てのサブノードを削除不可!", "ECC Information");
						return;
					}
				}
				else
				{
					return;
				}
			}
			else
			{
				if (EnumerateNode(objSelect, objArr) == false)
				{
					MessageBox.Show("全てのサブノードを削除不可!", "ECC Information");
					return;
				}
			}

			KindOfTempletEntity objentity = new KindOfTempletEntity();
			objentity = (KindOfTempletEntity)objSelect.Tag;
			ClsKindOfTemplet obj = new ClsKindOfTemplet();
			string strRet = obj.DeleteKindOfTemplet(objArr);

			if (strRet == "1")
			{
				MessageBox.Show("削除失敗!", "ECC Information");
			}
			else if (strRet != "")
			{
				MessageBox.Show(strRet, "ECC Catch Error");
			}
			else
			{
				objSelect.Remove();
			}
		}
		#endregion

		#region "EnumerateNode"
		private bool EnumerateNode(TreeNode objNode,ArrayList objArr)
		{
			KindOfTempletEntity objentity = new KindOfTempletEntity();
			objentity = (KindOfTempletEntity)objNode.Tag;
			ClsEmailTemplet objClsEmailTemplet = new ClsEmailTemplet();
			DataSet dtTmp = (DataSet)objClsEmailTemplet.GetListByID(objentity.KeyID);
			objArr.Add(objentity.KeyID);
			if (dtTmp.Tables.Count > 0 && dtTmp.Tables[0].Rows.Count > 0)
			{
				return false;
			}
			foreach (TreeNode tmp in objNode.Nodes)
			{
				if (EnumerateNode(tmp, objArr) == false)
				{
					return false;
				}
			}

			return true;
		}
		#endregion

		#region "tsmUpdate_Click"
		private void tsmUpdate_Click(object sender, EventArgs e)
		{
			tvClass.LabelEdit = true;
			TreeNode objSelect = new TreeNode();
			objSelect = this.tvClass.SelectedNode;
			objSelect.BeginEdit();
			TreeMode = 3;

		}
		#endregion

		#region "frmTemplateImportAndInput_Load"
		private void frmTemplateImportAndInput_Load(object sender, EventArgs e)
		{
			//if (ClsCommon.gStrRight != "Admin")
			//{
			//    btnImport.Enabled = false;
			//}

			if (intOpenMode == 1)
			{
				this.ControlBox = false;
			}

			TreeNode objTreeNode = new TreeNode();

			KindOfTempletEntity objentity = new KindOfTempletEntity();

			objentity.Type = 0;
			objentity.ParentNode = "0";
			objentity.ID = "1";
			objentity.Oreder = 0;
			objentity.Name = "Mail種類";
			Guid guid;
			guid = Guid.NewGuid();
			objentity.KeyID = guid.ToString();

			objTreeNode.ExpandAll();
			objTreeNode.Text = "Mail種類";
			objTreeNode.Name = "Mail種類";
			objTreeNode.Tag = objentity;
			this.tvClass.Nodes.Add(objTreeNode);

			NodesBind(objTreeNode);

			this.tvClass.ExpandAll();
			tvClass.LabelEdit = false;
			if (tvClass.Nodes.Count > 0)
			{
				if (tvClass.Nodes[0].Nodes.Count > 0)
				{
					objSelectNode = tvClass.Nodes[0].Nodes[0];
					tvClass.SelectedNode = tvClass.Nodes[0].Nodes[0];
					TreeNodeMouseClickEventArgs objTreeNodeMouseClickEventArgs =
						new TreeNodeMouseClickEventArgs(tvClass.SelectedNode, MouseButtons.Left, 1, objSelectNodeX, objSelectNodeY);
					tvClass_NodeMouseClick(null, objTreeNodeMouseClickEventArgs);
				}
			}

			intCheckBoxMode = 0;

			ReadXml();
		}

		private void Innit()
		{

			if (tvClass.Nodes.Count > 0)
			{
				if (objSelectNode != null)
				{
					tvClass.SelectedNode = objSelectNode;
					TreeNodeMouseClickEventArgs objTreeNodeMouseClickEventArgs =
						new TreeNodeMouseClickEventArgs(tvClass.SelectedNode, MouseButtons.Left, 1, objSelectNodeX, objSelectNodeY);
					tvClass_NodeMouseClick(null, objTreeNodeMouseClickEventArgs);
					tvClass.SelectedNode.Expand();
					tvClass.SelectedNode.ExpandAll();
				}
			}
		}

		#endregion

		#region "AddNode"
		private string AddNode(TreeNode objSelect, TreeNode objAdd)
		{
			KindOfTempletEntity objentityAdd = new KindOfTempletEntity();
			KindOfTempletEntity objentitySelect = new KindOfTempletEntity();

			objentitySelect = (KindOfTempletEntity)objSelect.Tag;

			objentityAdd.Type = TypeTemp.Enum_TypeTempAdd;
			objentityAdd.ParentNode = objentitySelect.ID;
			objentityAdd.ID = Convert.ToString(objentitySelect.ID.ToString() + "A" + (objAdd.Index + 1));
			objentityAdd.Oreder = objAdd.Index + 1;
			objentityAdd.Name = objAdd.Text;
			Guid guid;
			guid = Guid.NewGuid();
			objentityAdd.KeyID = guid.ToString();

			objAdd.Tag = objentityAdd;

			ClsKindOfTemplet obj = new ClsKindOfTemplet();
			ArrayList objArr = new ArrayList();
			objArr.Add(objentityAdd);
			string strRet = obj.AddKindOfTemplet(objArr);
			return strRet;

		}
		#endregion

		#region "DelNode"
		private string DelNode(TreeNode objSelect, TreeNode objAdd)
		{
			return "";
		}
		#endregion

		#region "UpdateNode"
		private string UpdateNode(TreeNode objAdd)
		{
			KindOfTempletEntity objentity = new KindOfTempletEntity();
			objentity = (KindOfTempletEntity)objAdd.Tag;
			objentity.Name = objAdd.Text;
			objAdd.Tag = objentity;

			ClsKindOfTemplet obj = new ClsKindOfTemplet();
			string strRet = obj.UpdateKindOfTemplet(objentity);
			return strRet;

		}
		#endregion

		#region "tvClass_AfterLabelEdit"
		private void tvClass_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
		{

			string strRet = "";
			string strName = "";
			switch (TreeMode)
			{
				case 1:
					if (e.Label == null)
					{
						e.Node.Remove();
						tvClass.LabelEdit = false;
						return;
					}

					if (e.Label.Trim() == "")
					{
						MessageBox.Show("テンプレートタイプ名は空白不可！", "ECC Information");
						e.Node.BeginEdit();
						return;
					}
					e.Node.Text = e.Label.Trim();
					e.Node.Name = e.Node.Text.Trim();

					if (CheckNode(e.Node) == false)
					{
						e.Node.Remove();
						TreeMode = 0;
						return;
					}
					strRet = AddNode(e.Node.Parent, e.Node);
					TreeMode = 0;
					break;
				case 2:
					strRet = DelNode(e.Node.Parent, e.Node);
					TreeMode = 0;
					break;
				case 3:
					strName = e.Node.Text;

					if (e.Label == null || e.Label == "")
					{
						MessageBox.Show("テンプレートタイプ名は空白不可", "ECC Information");
						TreeMode = 0;
						tvClass.LabelEdit = false;
						e.CancelEdit = true;
						return;
					}

					if (CheckNode(e.Node) == false)
					{
						e.CancelEdit = true;
						TreeMode = 0;
						tvClass.LabelEdit = false;
						return;
					}
					else
					{
						e.Node.Text = e.Label.Trim();
						e.Node.Name = e.Node.Text.Trim();

					}
					strRet = UpdateNode(e.Node);

					if (e.Node.Text != "")
					{
						e.Node.Text = strName;
					}
					TreeMode = 0;
					break;
				default:
					break;
			}

			if (strRet == "1")
			{
				MessageBox.Show("操作失敗！", "ECC Information");
			}
			else if (strRet != "")
			{
				MessageBox.Show(strRet, "ECC Catch Error");
			}

			tvClass.LabelEdit = false;

		}
		#endregion

		#region "CheckNode"
		private bool CheckNode(TreeNode objAdd)
		{
			if ((TreeMode == 1) || (TreeMode == 2))
			{
				if (objAdd.Text.Trim() == "")
				{
					MessageBox.Show("テンプレートタイプ名は空白不可！", "ECC Information");
					return false;
				}

				if (clsUICheck.CheckLen(objAdd.Text.Trim(), 50) == false)
				{
					MessageBox.Show("テンプレートタイプ名は入力长度超出！", "ECC Information");
				}

				TreeNode[] objArr = this.tvClass.Nodes.Find(objAdd.Text, true);

				if (objArr.Length > 0)
				{
					for (int i = 0; i < objArr.Length; i++)
					{
						if (objAdd != objArr[i])
						{
							MessageBox.Show("該当テンプレート名は既に存在、同じテンプレート名は創建できない。", "ECC Information");
							return false;
						}
					}

				}
			}

			return true;

		}
		#endregion

		#region "frmTemplateImportAndInput_FormClosed"
		private void frmTemplateImportAndInput_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (intOpenMode == 0)
			{

				Form frmMain = new frmMain();
				frmMain.Show();
			}
		}
		#endregion

		#region "tvClass_BeforeLabelEdit"
		private void tvClass_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
		{
			e.Node.Name = e.Node.Text.Trim();
		}
		#endregion

		#region "NodesBind"
		private void NodesBind(TreeNode objTreeNode)
		{
			TreeNode objTreeNodeAdd = new TreeNode();
			ClsKindOfTemplet obj = new ClsKindOfTemplet();
			DataSet dsTmp = new DataSet();
			dsTmp = (DataSet)obj.GetList();

			if ((dsTmp.Tables.Count == 0) || (dsTmp.Tables[0].Rows.Count == 0))
			{
				return;
			}

			System.Data.DataTable dtTmp = new System.Data.DataTable();
			dtTmp = dsTmp.Tables[0];
			DataView dvTmp = new DataView();
			DataView dvTmp1 = new DataView();
			dvTmp1 = dtTmp.DefaultView;
			dvTmp = dtTmp.DefaultView;
			if (ClsCommon.gStrRight == "Admin")
			{
				dvTmp = dvTmp1;
			}
			else
			{
				dvTmp1.RowFilter = "KindOftemplet_PersonalFlg = 0 or (KindOftemplet_PersonalFlg = 1 and KindOftemplet_UserID = " + ClsCommon.gIntOperatorID + ")";
				dvTmp = dvTmp1.ToTable().DefaultView;
				dtTmp = dvTmp1.ToTable();
			}

			for (int i = 0; i < dtTmp.Rows.Count; i++)
			{
				KindOfTempletEntity objentityAdd = new KindOfTempletEntity();
				dvTmp.RowFilter = "KindOfTemplet_ParentNode = '" + "1'";
				objTreeNodeAdd = null;
				if (dvTmp.Count == 0)
				{
					return;
				}
				else if (Convert.ToString(dtTmp.Rows[i]["KindOfTemplet_ParentNode"]) == "1")
				{
					objTreeNodeAdd = objTreeNode.Nodes.Add(dtTmp.Rows[i]["KindOfTemplet_Name"].ToString(),
																	dtTmp.Rows[i]["KindOfTemplet_Name"].ToString());
				}
				else
				{
					dvTmp.RowFilter = "KindOfTemplet_ID = '" + Convert.ToString(dtTmp.Rows[i]["KindOfTemplet_ParentNode"]) + "'";
					if (dvTmp.Count == 0)
					{

					}
					else
					{
						string strKey = dvTmp[0]["KindOfTemplet_Name"].ToString();

						TreeNode[] objArr = objTreeNode.Nodes.Find(strKey, true);

						if (objArr.Length > 0)
						{
							objTreeNodeAdd = objArr[0].Nodes.Add(dtTmp.Rows[i]["KindOfTemplet_Name"].ToString(),
									dtTmp.Rows[i]["KindOfTemplet_Name"].ToString());
						}

					}
				}
				if (objTreeNodeAdd != null)
				{
					objentityAdd.Type = 0;
					objentityAdd.ParentNode = Convert.ToString(dtTmp.Rows[i]["KindOfTemplet_ParentNode"]);
					objentityAdd.ID = Convert.ToString(dtTmp.Rows[i]["KindOfTemplet_ID"]);
					objentityAdd.Oreder = Convert.ToDouble(dtTmp.Rows[i]["KindOftemplet_Order"]);
					objentityAdd.Name = dtTmp.Rows[i]["KindOfTemplet_Name"].ToString();
					objentityAdd.KeyID = dtTmp.Rows[i]["KindOfTemplet_KeyID"].ToString().ToString();
					objTreeNodeAdd.Tag = objentityAdd;
				}
			}

			objTreeNode.ExpandAll();
		}

		#endregion

		#region "ctmTree_Opening"
		private void ctmTree_Opening(object sender, CancelEventArgs e)
		{
			if (this.tvClass.SelectedNode == null)
			{
				e.Cancel = true;
			}

			//if (this.tvClass.SelectedNode.Parent == null)
			//{
			//    ctmTree.Items["tsmDel"].Enabled = false;
			//    ctmTree.Items["tsmUpdate"].Enabled = false;
			//}
			//else
			//{
			//    ctmTree.Items["tsmDel"].Enabled = true;
			//    ctmTree.Items["tsmUpdate"].Enabled = true;
			//}

			if (ClsCommon.gStrRight != "Admin")
			{
				if (ctmTreeOpening(ClsCommon.gStrOperatorName,this.tvClass.SelectedNode) == false)
				{
					e.Cancel = true;
				}
			}
		}

		private bool ctmTreeOpening(string str,TreeNode objTreeNode)
		{
			if (objTreeNode != null)
			{
				if (objTreeNode.Text == str)
				{
					return true;
				}
				else
				{
					return ctmTreeOpening(str, objTreeNode.Parent);
				}
			}
			else
			{
				return false;
			}
		}

		#endregion

		#region "btnCommit_Click"
		private void btnCommit_Click(object sender, EventArgs e)
		{

			if (CheckKey() == false)
			{
				return;
			}

			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();
			KindOfTempletEntity objKindOfTempletEntity = new KindOfTempletEntity();
			ClsEmailTemplet objClsEmailTemplet = new ClsEmailTemplet();
			string strRet = "";

			this.dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = true;
			this.dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = true;
			objEmailTempletEntity.Name = this.dgwContent.Rows[intRowAddIndex].Cells["Key"].Value.ToString();
			objEmailTempletEntity.Order = Convert.ToInt32(this.dgwContent.Rows[intRowAddIndex].Cells["No"].Value.ToString().Trim());

			objEmailTempletEntity.PcContent = txtPC.Text;
			objEmailTempletEntity.ToteContent = txtPhone.Text;
			objEmailTempletEntity.Negotiation = txtContent.Text;
			if (ckTimeLimit.Checked == true)
			{
				objEmailTempletEntity.LimitedStartDate = dtpStart.Value;
				objEmailTempletEntity.LimitedEndDate = dtpEnd.Value;
				objEmailTempletEntity.TimeLimited = 1;
			}
			else
			{
				objEmailTempletEntity.LimitedStartDate = null;
				objEmailTempletEntity.LimitedEndDate = null;
				objEmailTempletEntity.TimeLimited = 0;
			}

			if (ckLimit.Checked == true)
			{
				objEmailTempletEntity.AvailabilitySign = 1;
			}
			else
			{
				objEmailTempletEntity.AvailabilitySign = 0;
			}

			if (chAttribute.Checked == true)
			{
				objEmailTempletEntity.Attribute = 1;
			}
			else
			{
				objEmailTempletEntity.Attribute = 0;
			}

			if (intEditMode == 1)
			{
				objEmailTempletEntity.ContentKeyID = Guid.NewGuid().ToString();
				objKindOfTempletEntity = (KindOfTempletEntity)this.tvClass.SelectedNode.Tag;
				objEmailTempletEntity.KeyID = objKindOfTempletEntity.KeyID;
				objEmailTempletEntity.CreatePerson = ClsCommon.gIntOperatorID;
				objEmailTempletEntity.UpdatePerson = null;
				objEmailTempletEntity.CreateDate = DateTime.Now;
				objEmailTempletEntity.UpdateDate = null;

				this.dgwContent.Rows[intRowAddIndex].Tag = objEmailTempletEntity;
				ArrayList objarr = new ArrayList();
				objarr.Add(objEmailTempletEntity);
				strRet = objClsEmailTemplet.AddEmailTemplet(objarr);
				if (strRet != "")
				{
					dgwContent.Rows.RemoveAt(intRowAddIndex);
				}
				else
				{
					dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = true;
					dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = true;
				}

			}
			else if (intEditMode == 2)
			{
				EmailTempletEntity objEmailTempletEntityTmp = new EmailTempletEntity();
				objEmailTempletEntityTmp = (EmailTempletEntity)this.dgwContent.Rows[intRowAddIndex].Tag;
				objEmailTempletEntity.ContentKeyID = objEmailTempletEntityTmp.ContentKeyID;
				objEmailTempletEntity.KeyID = objEmailTempletEntityTmp.KeyID;
				objEmailTempletEntity.CreatePerson = (int)txtCreatePreson.Tag;
				objEmailTempletEntity.CreatePersonName = txtCreatePreson.Text;
				objEmailTempletEntity.UpdatePerson = ClsCommon.gIntOperatorID;
				objEmailTempletEntity.UpdatePersonName = txtUpdatePerson.Text;
				objEmailTempletEntity.CreateDate = dtpCreateDate.Value;
				objEmailTempletEntity.UpdateDate = DateTime.Now;

				this.dgwContent.Rows[intRowAddIndex].Tag = objEmailTempletEntity;

				strRet = objClsEmailTemplet.UpdateEmailTemplet(objEmailTempletEntity);

				if (strRet == "")
				{
					dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = true;
					dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = true;
				}

			}
			else if (intEditMode == 3)
			{
				if (MessageBox.Show("当該テンプレートは削除しますか？", "ECC Information", MessageBoxButtons.YesNo) != DialogResult.Yes)
				{
					return;
				}
				objEmailTempletEntity = (EmailTempletEntity)this.dgwContent.Rows[intRowAddIndex].Tag;

				strRet = objClsEmailTemplet.DeleteEmailTemplet(objEmailTempletEntity.ContentKeyID);

				if (strRet == "")
				{
					dgwContent.Rows.RemoveAt(intRowAddIndex);
				}

				txtContent.Text = "";
				txtPC.Text = "";
				txtPhone.Text = "";
			}

			if (intEditMode != 3)
			{
				dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = true;
				dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = true;
				//txtPC.ReadOnly = true;
				//txtPhone.ReadOnly = true;
				//txtContent.ReadOnly = true;
			}

			if (strRet == "1")
			{
				MessageBox.Show("データ操作失敗!", "ECC Information");
			}
			else if (strRet != "")
			{
				MessageBox.Show(strRet, "ECC Catch Error");
			}

			intEditMode = 0;

			InitInput(true);
			InitButton(true);
		}
		#endregion

		#region "注释掉的"

		//private void tsmKeyAdd_Click(object sender, EventArgs e)
		//{
		//    if (this.tvClass.SelectedNode == null || this.tvClass.SelectedNode.Parent == null)
		//    {
		//        MessageBox.Show("请选择类型！", "ECC Information");
		//        return;
		//    }	

		//    EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();

		//    intEditMode = 1;
		//    intModeButton = 1;
		//    InitButton();
		//    intRowAddIndex = dgwContent.Rows.Add();
		//    intOldRowIndex = intRowAddIndex;
		//    this.dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = false;
		//    this.dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = false;
		//    this.dgwContent.Rows[intRowAddIndex].Tag = objEmailTempletEntity;
		//    this.dgwContent.Rows[intRowAddIndex].Selected = true;
		//    InitInput(false);

		//}

		//private void tsmKeyDel_Click(object sender, EventArgs e)
		//{
		//    intRowAddIndex = dgwContent.SelectedRows[0].Index;
		//    intEditMode = 3;
		//}

		//private void tsmKeyUpdate_Click(object sender, EventArgs e)
		//{
		//    intEditMode = 2;
		//    intRowAddIndex = dgwContent.SelectedRows[0].Index;
		//    dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = false;
		//    dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = false;

		//    InitInput(false);

		//}

		//private void ctmKey_Opening(object sender, CancelEventArgs e)
		//{
		//    if (intEditMode != 0)
		//    {
		//        MessageBox.Show("画面内容变更,请更新！", "ECC Information");
		//        e.Cancel = true; ;
		//    }
		//    if (this.dgwContent.SelectedRows == null)
		//    {
		//        ctmKey.Items["tsmKeyDel"].Enabled = false;
		//        ctmKey.Items["tsmKeyUpdate"].Enabled = false;
		//    }
		//    else
		//    {
		//        ctmKey.Items["tsmKeyDel"].Enabled = true;
		//        ctmKey.Items["tsmKeyUpdate"].Enabled = true;
		//    }
		//}

		#endregion

		#region "InitButton"
		private void InitButton(bool bl)
		{
			btnImport.Enabled = bl;
			btnAdd.Enabled = bl;
			btnDel.Enabled = bl;
			btnUpdate.Enabled = bl;
			btnCommit.Enabled = !bl;
			btnCancel.Enabled = !bl;
			//if (ClsCommon.gStrRight != "Admin")
			//{
			//    btnImport.Enabled = false;
			//}
		}
		#endregion

		#region "CheckKey"

		private bool CheckKey()
		{
			if (ClsCommon.gStrRight != "Admin" && chAttribute.Checked == false)
			{
				MessageBox.Show("当該ファイル名は私有である。", "ECC Information");
				return false;
			}

			if (this.dgwContent.Rows[intRowAddIndex].Cells["No"].Value.ToString().Trim() == "")
			{
				MessageBox.Show("案内文番号入力必須!", "ECC Information");
				return false;
			}

			if (clsUICheck.isNum(this.dgwContent.Rows[intRowAddIndex].Cells["No"].Value.ToString().Trim()) == false)
			{
				MessageBox.Show("案内文番号は数字必須!", "ECC Information");
				return false;
			}

			if (this.dgwContent.Rows[intRowAddIndex].Cells["Key"].Value.ToString().Trim() == "")
			{
				MessageBox.Show("件名入力必須!", "ECC Information");
				return false;
			}

			for (int i = 0; i < dgwContent.Rows.Count; i++)
			{
				if (intRowAddIndex != i)
				{
					if (dgwContent.Rows[i].Cells["No"].Value.ToString().Trim() ==
							dgwContent.Rows[intRowAddIndex].Cells["No"].Value.ToString().Trim())
					{
						MessageBox.Show("案内文番号重複，保存不可!", "ECC Information");
						return false;
					}

					if (dgwContent.Rows[i].Cells["Key"].Value.ToString().Trim() ==
							dgwContent.Rows[intRowAddIndex].Cells["Key"].Value.ToString().Trim())
					{
						MessageBox.Show("件名重複，保存不可!", "ECC Information");
						return false;
					}
				}

			}

			if (clsUICheck.CheckLen(this.dgwContent.Rows[intRowAddIndex].Cells["Key"].Value.ToString().Trim(), 60) == false)
			{
				MessageBox.Show("件名入力長さは長すぎ!", "ECC Information");
				return false;
			}

			if ((dtpEnd.Value < dtpStart.Value) && (ckTimeLimit.Checked == true))
			{
				MessageBox.Show("時効終了日付は開始日付より遅い!", "ECC Information");
				return false;
			}



			return true;

		}
		#endregion

		#region "ckTimeLimit_CheckedChanged"
		private void ckTimeLimit_CheckedChanged(object sender, EventArgs e)
		{
			if (ckTimeLimit.Checked == true)
			{
				dtpStart.Enabled = true;
				dtpEnd.Enabled = true;
			}
			else
			{
				dtpStart.Enabled = false;
				dtpEnd.Enabled = false;
			}
		}
		#endregion

		#region "tvClass_NodeMouseClick"

		private void tvClass_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			objSelectNode = e.Node;
			objSelectNodeX = e.X;
			objSelectNodeY = e.Y;
			ClsEmailTemplet objClsEmailTemplet = new ClsEmailTemplet();

			KindOfTempletEntity objKindOfTempletEntity = new KindOfTempletEntity();
			objKindOfTempletEntity = (KindOfTempletEntity)e.Node.Tag;

			DataSet dtTmp = (DataSet)objClsEmailTemplet.GetListByID(objKindOfTempletEntity.KeyID);

			dgwContent.Rows.Clear();
			this.dgwContent.AutoGenerateColumns = false;

			if (dtTmp.Tables.Count > 0 && dtTmp.Tables[0].Rows.Count > 0)
			{
				//System.Data.DataTable dtObj = new System.Data.DataTable();
				//dtObj = dtTmp.Tables[0];
				//dtObj.Columns.Add("check");
				//for (int i = 0; i < dtTmp.Tables[0].Rows.Count; i++)
				//{
				//    dtObj.Rows[i]["check"] = 0;
				//}

				//dgwContent.DataSource = dtObj;
				for (int i = 0; i < dtTmp.Tables[0].Rows.Count; i++)
				{
					DataRow dr = dtTmp.Tables[0].Rows[i];
					dgwContent.Rows.Add(new object[] { false, dr["EmailTemplet_Order"].ToString(), dr["EmailTemplet_Name"].ToString() });
					//dgwContent.Rows.Add(new object[] { 0, dr["EmailTemplet_Order"].ToString(), dr["EmailTemplet_Name"].ToString() });
					dgwContent.Rows[i].Tag = BindEmailTempletEntity(dtTmp.Tables[0].Rows[i]);
					dgwContent.Rows[i].Cells["No"].ReadOnly = true;
					dgwContent.Rows[i].Cells["Key"].ReadOnly = true;
				}
				BindForm((EmailTempletEntity)dgwContent.Rows[0].Tag);
				dtpStart.Enabled = false;
				dtpEnd.Enabled = false;
			}

			intCheckBoxMode = 0;
			intValueChangeMode = 1;
		}
		#endregion

		#region "BindEmailTempletEntity"

		private EmailTempletEntity BindEmailTempletEntity(DataRow dr)
		{
			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();

			if (dr["EmailContent_AvailabilitySign"] != System.DBNull.Value)
			{
				objEmailTempletEntity.AvailabilitySign = Convert.ToInt32(dr["EmailContent_AvailabilitySign"]);
			}

			if (dr["EmailContent_CreateDate"] != System.DBNull.Value)
			{
				objEmailTempletEntity.CreateDate = Convert.ToDateTime(dr["EmailContent_CreateDate"]);
			}
			else
			{
				objEmailTempletEntity.CreateDate = null;
			}

			if (dr["EmailContentKeyID"] != System.DBNull.Value)
			{
				objEmailTempletEntity.ContentKeyID = Convert.ToString(dr["EmailContentKeyID"]);
			}

			if (dr["EmailContent_CreatePerson"] != System.DBNull.Value)
			{
				objEmailTempletEntity.CreatePerson = Convert.ToInt32(dr["EmailContent_CreatePerson"]);
			}
			else
			{
				objEmailTempletEntity.CreatePerson = null;
			}

			if (dr["CreateName"] != System.DBNull.Value)
			{
				objEmailTempletEntity.CreatePersonName = Convert.ToString(dr["CreateName"]);
			}
			else
			{
				objEmailTempletEntity.CreatePersonName = "";
			}

			if (dr["KindOfTemplet_KeyID"] != System.DBNull.Value)
			{
				objEmailTempletEntity.KeyID = Convert.ToString(dr["KindOfTemplet_KeyID"]);
			}
			else
			{
				objEmailTempletEntity.KeyID = "";
			}

			if (dr["EmailContent_TimeLimitedEndDate"] != System.DBNull.Value)
			{
				objEmailTempletEntity.LimitedEndDate = Convert.ToDateTime(dr["EmailContent_TimeLimitedEndDate"]);
			}
			else
			{
				objEmailTempletEntity.LimitedEndDate = null;
			}

			if (dr["EmailContent_TimeLimitedStartDate"] != System.DBNull.Value)
			{
				objEmailTempletEntity.LimitedStartDate = Convert.ToDateTime(dr["EmailContent_TimeLimitedStartDate"]);
			}
			else
			{
				objEmailTempletEntity.LimitedStartDate = null;
			}

			if (dr["EmailTemplet_Name"] != System.DBNull.Value)
			{
				objEmailTempletEntity.Name = Convert.ToString(dr["EmailTemplet_Name"]);
			}
			else
			{
				objEmailTempletEntity.Name = "";
			}

			if (dr["EmailContent_Negotiation"] != System.DBNull.Value)
			{
				objEmailTempletEntity.Negotiation = Convert.ToString(dr["EmailContent_Negotiation"]);
			}
			else
			{
				objEmailTempletEntity.Negotiation = "";
			}

			if (dr["EmailTemplet_Order"] != System.DBNull.Value)
			{
				objEmailTempletEntity.Order = Convert.ToInt32(dr["EmailTemplet_Order"]);
			}
			else
			{
				objEmailTempletEntity.Order = null;
			}

			if (dr["EmailTemplet_Attribute"] != System.DBNull.Value)
			{
				objEmailTempletEntity.Attribute = Convert.ToInt32(dr["EmailTemplet_Attribute"]);
			}
			else
			{
				objEmailTempletEntity.Attribute = 0;
			}

			if (dr["EmailContent_PcContent"] != System.DBNull.Value)
			{
				objEmailTempletEntity.PcContent = Convert.ToString(dr["EmailContent_PcContent"]);
			}
			else
			{
				objEmailTempletEntity.PcContent = "";
			}

			if (dr["EmailContent_TimeLimited"] != System.DBNull.Value)
			{
				objEmailTempletEntity.TimeLimited = Convert.ToInt32(dr["EmailContent_TimeLimited"]);
			}

			if (dr["EmailContent_ToteContent"] != System.DBNull.Value)
			{
				objEmailTempletEntity.ToteContent = Convert.ToString(dr["EmailContent_ToteContent"]);
			}
			else
			{
				objEmailTempletEntity.ToteContent = "";
			}

			if (dr["EmailContent_UpdateDate"] != System.DBNull.Value)
			{
				objEmailTempletEntity.UpdateDate = Convert.ToDateTime(dr["EmailContent_UpdateDate"]);
			}
			else
			{
				objEmailTempletEntity.UpdateDate = null;
			}

			if (dr["EmailContent_UpdatePerson"] != System.DBNull.Value)
			{
				objEmailTempletEntity.UpdatePerson = Convert.ToInt32(dr["EmailContent_UpdatePerson"]);
			}
			else
			{
				objEmailTempletEntity.UpdatePerson = null;
			}

			if (dr["UpdateName"] != System.DBNull.Value)
			{
				objEmailTempletEntity.UpdatePersonName = Convert.ToString(dr["UpdateName"]);
			}
			else
			{
				objEmailTempletEntity.UpdatePersonName = "";
			}

			if (dr["Rule_KeyID"] != System.DBNull.Value)
			{
				objEmailTempletEntity.Rule_KeyID = Convert.ToString(dr["Rule_KeyID"]);
				objEmailTempletEntity.RuleName = Convert.ToString(dr["Rule_caption"]);
			}
			else
			{
				objEmailTempletEntity.Rule_KeyID = "";
				objEmailTempletEntity.RuleName = "";
			}

			if (dr["Rule_RuleUserID"] != System.DBNull.Value)
			{
				objEmailTempletEntity.Rule_RuleUserID = Convert.ToString(dr["Rule_RuleUserID"]);
			}
			else
			{
				objEmailTempletEntity.Rule_RuleUserID = "";
			}

			return objEmailTempletEntity;
		}

		#endregion

		#region "BindForm"

	    private EmailTempletEntity _emailTempletEntity; //Ext 2012.9.26
		private void BindForm(EmailTempletEntity objEmailTempletEntity)
		{
            _emailTempletEntity = objEmailTempletEntity; //Ext 2012.9.26

			if (objEmailTempletEntity.CreateDate != null)
			{
				dtpCreateDate.Value = objEmailTempletEntity.CreateDate.Value;
			}

			if (objEmailTempletEntity.UpdateDate != null)
			{
				dtpUpdateDate.Value = objEmailTempletEntity.UpdateDate.Value;
			}

			txtCreatePreson.Text = objEmailTempletEntity.CreatePersonName;

			txtCreatePreson.Tag = objEmailTempletEntity.CreatePerson;

			txtUpdatePerson.Text = objEmailTempletEntity.UpdatePersonName;

			txtUpdatePerson.Tag = objEmailTempletEntity.UpdatePerson;

			txtPhone.Text = objEmailTempletEntity.ToteContent;

			txtPC.Text = objEmailTempletEntity.PcContent;

			if (intCheckBoxMode != 1)
			{
				txtContent.Text = objEmailTempletEntity.Negotiation;
			}

			if (objEmailTempletEntity.Attribute == 1)
			{
				chAttribute.Checked = true;
			}
			else
			{
				chAttribute.Checked = false;
			}

			if (objEmailTempletEntity.AvailabilitySign == 1)
			{
				ckLimit.Checked = true;
			}
			else
			{
				ckLimit.Checked = false;
			}

			if (objEmailTempletEntity.TimeLimited == 1)
			{
				ckTimeLimit.Checked = true;
				dtpStart.Value = objEmailTempletEntity.LimitedStartDate.Value;
				dtpStart.Enabled = true;
				dtpEnd.Value = objEmailTempletEntity.LimitedEndDate.Value;
				dtpEnd.Enabled = true;
			}
			else
			{
				ckTimeLimit.Checked = false;
				dtpStart.Enabled = false;
				dtpEnd.Enabled = false;
			}

		}
		#endregion

		#region "dgwContent_CellClick"
		private void dgwContent_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();
			if (intEditMode != 0)
			{
				dgwContent.Rows[intOldRowIndex].Selected = true;
				return;
			}
			objEmailTempletEntity = null;

			objEmailTempletEntity = (EmailTempletEntity)dgwContent.Rows[e.RowIndex].Tag;
			if (objEmailTempletEntity.Rule_KeyID != null)
			{
				if (objEmailTempletEntity.Rule_KeyID != "")
				{
					string[] strArr = objEmailTempletEntity.Rule_RuleUserID.Split(new char[] { Convert.ToChar("|") });
                    //for (int i = 0; i < strArr.Length; i++)
                    //{
                    //    if (strArr[i] == ClsCommon.gIntOperatorID.ToString())
                    //    {
                            dgwContent.Rows[e.RowIndex].Selected = false;
							    frmRuleMessage objfrmRuleMessage = new frmRuleMessage(objEmailTempletEntity.RuleName);
							    objfrmRuleMessage.ShowDialog();
                            dgwContent.Rows[e.RowIndex].Selected = false;
							    //MessageBox.Show("当該件名の規則を注意して下さい!", "ECC Information");
                    //     }
                    //}
				}
			}


			intOldRowIndex = e.RowIndex;
			BindForm(objEmailTempletEntity);
			dtpStart.Enabled = false;
			dtpEnd.Enabled = false;

		}
		#endregion

		#region "InitInput"
		private void InitInput(bool bl)
		{
			//txtPC.ReadOnly = bl;
			//txtPhone.ReadOnly = bl;
			//txtContent.ReadOnly = bl;
			ckLimit.Enabled = !bl;
			ckLimit.Checked = !bl;
			ckTimeLimit.Checked = !bl;
			ckTimeLimit.Enabled = !bl;
			chAttribute.Checked = !bl;
			chAttribute.Enabled = !bl;
			dtpStart.Enabled = !bl;
			dtpEnd.Enabled = !bl;
			tvClass.Enabled = bl;
		}
		#endregion

		#region "btnAdd_Click"

		private void btnAdd_Click(object sender, EventArgs e)
		{
			if (CheckButton() == false)
			{
				return;
			}
			if (ClsCommon.gStrRight != "Admin")
			{
				chAttribute.Checked = true;
			}

			if (this.tvClass.SelectedNode == null || this.tvClass.SelectedNode.Parent == null)
			{
				MessageBox.Show("タイプを選択して下さい！", "ECC Information");
				return;
			}

			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();

			intEditMode = 1;
			InitButton(false);
			intRowAddIndex = dgwContent.Rows.Add();
			intOldRowIndex = intRowAddIndex;
			this.dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = false;
			this.dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = false;
			this.dgwContent.Rows[intRowAddIndex].Cells["No"].Value = "";
			this.dgwContent.Rows[intRowAddIndex].Cells["Key"].Value = "";
			this.dgwContent.Rows[intRowAddIndex].Tag = objEmailTempletEntity;
			this.dgwContent.Rows[intRowAddIndex].Selected = true;
			InitInput(false);

		}
		#endregion

		#region "btnDel_Click"

		private void btnDel_Click(object sender, EventArgs e)
		{

			if (dgwContent.Rows.Count == 0)
			{
				return;
			}

			if (CheckButton() == false)
			{
				return;
			}
			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();
			objEmailTempletEntity = (EmailTempletEntity)dgwContent.SelectedRows[0].Tag;
			if (BizRule.ClsCommon.gStrRight != "Admin" )
			{
				if (objEmailTempletEntity.Attribute != 1)
				{
					return;
				}
				
			}

			InitButton(false);
			intRowAddIndex = dgwContent.SelectedRows[0].Index;
			intEditMode = 3;
		}
		#endregion

		#region "btnCancel_Click"

		private void btnCancel_Click(object sender, EventArgs e)
		{

			InitButton(true);
			InitInput(true);

			if (intEditMode == 1)
			{
				dgwContent.Rows.RemoveAt(intRowAddIndex);
			}
			intEditMode = 0;
		}
		#endregion

		#region "CheckButton"

		private bool CheckButton()
		{
			if (intEditMode != 0)
			{
				MessageBox.Show("画面内容は変更し、保存必要!", "ECC Information");
				return false;
			}
			if (this.dgwContent.SelectedRows == null)
			{
				MessageBox.Show("操作必要の件名を選択して下さい!", "ECC Information");
				return false;
			}

			return true;
		}
		#endregion

		#region "btnUpdate_Click"

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			if (dgwContent.Rows.Count == 0)
			{
				return;
			}

			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();

			objEmailTempletEntity = (EmailTempletEntity)dgwContent.SelectedRows[0].Tag;
			if (BizRule.ClsCommon.gStrRight != "Admin")
			{
				if (objEmailTempletEntity.Attribute != 1)
				{
					return;
				}

			}
			intEditMode = 2;
			intRowAddIndex = dgwContent.SelectedRows[0].Index;
			dgwContent.Rows[intRowAddIndex].Cells["No"].ReadOnly = false;
			dgwContent.Rows[intRowAddIndex].Cells["Key"].ReadOnly = false;

			InitButton(false);
			InitInput(false);
		}
		#endregion

		#region "frmTemplateImportAndInput_FormClosing"
		private void frmTemplateImportAndInput_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (intEditMode == 1 || intEditMode == 2)
			{
				if (MessageBox.Show("画面内容は変更し、保存必要!", "ECC Information", MessageBoxButtons.YesNo) == DialogResult.Yes)
				{
					btnCommit_Click(null, null);
					e.Cancel = true;
				}
			}

			SaveXml();
		}

		#endregion

		#region "dgwContent_CellValueChanged"

		private void dgwContent_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			if (intCheckBoxMode == 3)
			{
				return;
			}

			if (intValueChangeMode == 0)
			{
				intValueChangeMode = 1;
				return;
			}
			EmailTempletEntity objEmailTempletEntity = new EmailTempletEntity();
			if (e.ColumnIndex == 0)
			{
				System.Windows.Forms.CheckBox ckTmp = new System.Windows.Forms.CheckBox();

				if (dgwContent.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
				{
					intCheckBoxMode = 1;

					for (int i = 0; i < dgwContent.Rows.Count; i++)
					{
						//ckTmp = (System.Windows.Forms.CheckBox)dgwContent.Rows[i].Cells[e.ColumnIndex];
						if (i != e.RowIndex && dgwContent.Rows[i].Cells[e.ColumnIndex].Value.ToString() == "1")
						{
							if (MessageBox.Show("メインテンプレートを変更しますか?", "ECC Information", MessageBoxButtons.YesNo) == DialogResult.Yes)
							{
								objEmailTempletEntity = (EmailTempletEntity)dgwContent.Rows[e.RowIndex].Tag;
								intCheckBoxMode = 1;
								this.txtContent.Text = objEmailTempletEntity.Negotiation;
								intValueChangeMode = 0;
								dgwContent.Rows[i].Cells[e.ColumnIndex].Value = "0";
							}
							else
							{
								intValueChangeMode = 0;
								dgwContent.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "0";
							}
						}
					}
				}
				else
				{
					intCheckBoxMode = 0;
				}

			}
		}

		#endregion

		#region "dgwContent_CellMouseUp"

		private void dgwContent_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
		{

			if (e.ColumnIndex == 0)
			{				
				dgwContent.Rows[e.RowIndex].Cells[1].Selected = true;
			}
			//int intCol = e.ColumnIndex;
			//int intRow = e.RowIndex;
			//if (dgwContent.Rows.Count > 1)
			//{
			//    if (dgwContent.Rows.Count != e.RowIndex + 1)
			//    {
			//        dgwContent.Rows[e.RowIndex + 1] = true;
			//    }
			//    else
			//    {
			//        dgwContent.Rows[e.RowIndex - 1].Selected = true;
			//    }

			//    dgwContent.Rows[e.RowIndex].Selected = true;
			//}
		}
		#endregion

		#region "btnSearch_Click"

		public void btnSearch_Click(object sender, EventArgs e)
		{
			string strwhere = "";
			string strTmp = "";
			string strColName = "";
			if (txtSearchKey.Text.Trim() == "")
			{
				MessageBox.Show("検索条件を入力して下さい!", "ECC Information");
				return;
			}
			strwhere = strwhere + "( ";

			//strwhere = strwhere + "( ";
			//if (txtSearchClass.Text.Trim() != "")
			//{
				
			//    strTmp = txtSearchClass.Text.Trim();
			//    while (strTmp.Contains("  ") || strTmp.Contains("　　"))
			//    {
			//        strTmp.Replace("  ", " ");
			//        strTmp.Replace("　　", " ");
			//    }

			//    while (strTmp.Contains("++") || strTmp.Contains("＋＋"))
			//    {
			//        strTmp.Replace("++", "+");
			//        strTmp.Replace("＋＋", "+");
			//    }

			//    string[] strArrWhere = strTmp.Split(new char[] {Convert.ToChar("+")});

			//    for (int i = 0; i < strArrWhere.Length; i++)
			//    {
			//        if (strArrWhere[i] != "")
			//        {
			//            string[] strArrWhereTmp = strArrWhere[i].Trim().Split(new char[] { Convert.ToChar(" ") });
			//            for (int j = 0; j < strArrWhereTmp.Length; j++)
			//            {
			//                if (strArrWhereTmp.Length == 1 || j == strArrWhereTmp.Length - 1)
			//                {
			//                    strwhere = strwhere + "d.KindOfTemplet_Name like N'%" + strArrWhereTmp[j] + "%' and ";
			//                }
			//                else
			//                {
			//                    strwhere = strwhere + "d.KindOfTemplet_Name like N'%" + strArrWhereTmp[j] + "%' or ";
			//                }
							
			//            }
			//        }
			//    }
			//}

			//strwhere = strwhere + " 1 = 1)";
			//strwhere = strwhere + " or (";
			if (txtSearchKey.Text.Trim() != "")
			{
				

				strTmp = txtSearchKey.Text.Trim();
				while (strTmp.Contains("  ") || strTmp.Contains("　　"))
				{
					strTmp.Replace("  ", " ");
					strTmp.Replace("　　", " ");
				}

				while (strTmp.Contains("++") || strTmp.Contains("＋＋"))
				{
					strTmp.Replace("++", "+");
					strTmp.Replace("＋＋", "+");
				}

				string[] strArrWhere = strTmp.Split(new char[] { Convert.ToChar("+") });

				for (int i = 0; i < strArrWhere.Length; i++)
				{
					if (strArrWhere[i] != "")
					{
						string[] strArrWhereTmp = strArrWhere[i].Trim().Split(new char[] { Convert.ToChar(" ") });
						for (int j = 0; j < strArrWhereTmp.Length; j++)
						{
							if (strArrWhereTmp.Length == 1 || j == strArrWhereTmp.Length - 1)
							{
								strwhere = strwhere + "a.EmailTemplet_Name like N'%" + strArrWhereTmp[j] + "%' and ";
							}
							else
							{
								strwhere = strwhere + "a.EmailTemplet_Name like N'%" + strArrWhereTmp[j] + "%' or ";
							}

						}
					}
				}

				strwhere = strwhere + " 1 = 1 )";
			}
			
			strwhere.Replace("or  1 = 1 ","");
			strwhere.Replace(" and  1 = 1 ", "");

			switch (cmbSearch.Text)
			{
				case "件名":
					break;
				case "内容":
					strColName = strwhere;
					strwhere = strColName.Replace("EmailTemplet_Name","EmailContent_PcContent") + " or " + strColName.Replace("EmailTemplet_Name","EmailContent_ToteContent");
					break;
				case "全部":
					strColName = strwhere;
					strwhere = strwhere + " or " + strColName.Replace("EmailTemplet_Name","EmailContent_PcContent") + " or " + strColName.Replace("EmailTemplet_Name","EmailContent_ToteContent");
					break;

				default:
					break;
			}

			strwhere = "(" + strwhere + ")" + " and ((a.EmailTemplet_Attribute = 1 and a.EmailContent_CreatePerson = '"
				+ ClsCommon.gIntOperatorID + "' ) or a.EmailTemplet_Attribute = 0)";

			ClsEmailTemplet objClsEmailTemplet = new ClsEmailTemplet();
			DataSet dtTmp = (DataSet)objClsEmailTemplet.GetListByName(strwhere);

			dgwContent.Rows.Clear();
			this.dgwContent.AutoGenerateColumns = false;

			if (dtTmp.Tables.Count > 0 && dtTmp.Tables[0].Rows.Count > 0)
			{
				for (int i = 0; i < dtTmp.Tables[0].Rows.Count; i++)
				{
					DataRow dr = dtTmp.Tables[0].Rows[i];
					dgwContent.Rows.Add(new object[] { false, dr["EmailTemplet_Order"].ToString(), dr["EmailTemplet_Name"].ToString() });
					dgwContent.Rows[i].Tag = BindEmailTempletEntity(dtTmp.Tables[0].Rows[i]);
					dgwContent.Rows[i].Cells["No"].ReadOnly = true;
					dgwContent.Rows[i].Cells["Key"].ReadOnly = true;
				}
				BindForm((EmailTempletEntity)dgwContent.Rows[0].Tag);
				dtpStart.Enabled = false;
				dtpEnd.Enabled = false;
			}

			intCheckBoxMode = 0;
			intValueChangeMode = 1;

			strTmp = txtSearchKey.Text.Replace("【", "").Replace("】", "");

			TreeNode[] objTreeNodeArr = null;

			objTreeNodeArr = this.tvClass.Nodes.Find(strTmp, true);

			if (objTreeNodeArr != null)
			{
				if (objTreeNodeArr.Length > 0)
				{
					this.tvClass.SelectedNode = objTreeNodeArr[0];
					objSelectNode = this.tvClass.SelectedNode;
				}
			}


		}
		#endregion

		#region "ReadXml"
		private void ReadXml()
		{
			XmlDocument xd = new XmlDocument();
			string str = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
			xd.Load(str + "xmlSet.xml");
			XmlNode node = xd.SelectSingleNode("//Page");
			int nodesCount = node.ChildNodes.Count;
			for (int i = 0; i < nodesCount; i++)
			{

				string name = node.ChildNodes[i].LocalName;
				if ("height".Equals(name))
				{
					if (node.ChildNodes[i].InnerText == null)
					{
						
					}
					else
					{
						this.Height = Convert.ToInt32(node.ChildNodes[i].InnerText);
					}

				}

				if ("width".Equals(name))
				{
					if (node.ChildNodes[i].InnerText == null)
					{
						
					}
					else
					{
						this.Width = Convert.ToInt32(node.ChildNodes[i].InnerText);
					}
				}
			}

		}
		#endregion

		#region "SaveXml"
		private void SaveXml()
		{
			XmlDocument xd = new XmlDocument();
			string str = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
			xd.Load(str + "xmlSet.xml");
			XmlNode node = xd.SelectSingleNode("//Page");
			int nodesCount = node.ChildNodes.Count;
			for (int i = 0; i < nodesCount; i++)
			{
				string name = node.ChildNodes[i].LocalName;
				if ("height".Equals(name))
				{
					node.ChildNodes[i].InnerText = this.Height.ToString();
				}

				if ("width".Equals(name))
				{
					node.ChildNodes[i].InnerText = this.Width.ToString();
				}
			}

			xd.Save(str + "xmlSet.xml");
		}
		#endregion


		private string FormatString(string strText)
		{
			string strTmp = "";
			string strFormat = "";
			int flg = 0;
			if (strText == "")
			{
				return "";
			}
			int intCount = 0;

			if (UnicodeEncoding.Default.GetByteCount(strText) <= 44)
			{
				strFormat = strFormat + strText + "▓" + "\r\n";
				return strFormat;
			}

			for (int i = 0; i < strText.Length; i++)
			{
				strTmp = strText.Substring(i, 1);
				int intTmp = UnicodeEncoding.Default.GetByteCount(strTmp);

				intCount = intCount + intTmp;
				if (flg == 0)
				{
					if (intCount == 44)
					{
						intCount = 0;
						strFormat = strFormat + strTmp + "▓" + "\r\n" + ">";
						flg = 1;
					}
					else if (intCount == 45)
					{
						intCount = 0;
						i = i - 1;
						strFormat = strFormat + "▓" + "\r\n" + ">";
						flg = 1;
					}
					else
					{
						strFormat = strFormat + strTmp;
					}
					
				}
				else
				{
					if (intCount == 43)
					{
						intCount = 0;
						strFormat = strFormat + strTmp + "▓" + "\r\n" + ">";
					}
					else if (intCount == 44)
					{
						intCount = 0;
						i = i - 1;
						strFormat = strFormat + "▓" + "\r\n" + ">";
					}
					else
					{
						strFormat = strFormat + strTmp;
					}
				}
				


			}

			strFormat = strFormat + "▓" + "\r\n";


			//if (strText.Length <= 22)
			//{
			//    strFormat = strFormat + strText + "▓" + "\r\n";
			//    return strFormat;
			//}


			//while (strText.Length > 21)
			//{
			//    if (flg == 0)
			//    {
			//        strTmp = strText.Substring(0, 22);
			//        strFormat = strFormat + strTmp + "▓" + "\r\n";
			//        strText = strText.Substring(22);
			//        flg = 1;
			//    }
			//    else
			//    {
			//        strTmp = strText.Substring(0, 21);
			//        strFormat = strFormat + ">" + strTmp + "▓" + "\r\n";
			//        strText = strText.Substring(21);
			//    }

			//}

			//strFormat = strFormat + ">" + strText + "▓" + "\r\n";
			return strFormat;
			
		}

		private void txtContent_Validating(object sender, CancelEventArgs e)
		{
			string strTmp = "";
			strTmp = txtContent.Text.Trim();
			strTmp = strTmp.Replace(">", "");
			strTmp = strTmp.Replace("▓", "");
			strTmp = strTmp.Replace("\r\n", "");
			txtContent.Tag = strTmp;
			txtContent.Text = FormatString(strTmp);
		}

		private void txtContent_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				string strTmp = "";
				strTmp = txtContent.Text.Trim();
				strTmp = strTmp.Replace(">", "");
				strTmp = strTmp.Replace("▓", "");
				strTmp = strTmp.Replace("\r\n", "");
				txtContent.Tag = strTmp;
				txtContent.Text = FormatString(strTmp);
			}
		}

		private void txtContent_DoubleClick(object sender, EventArgs e)
		{
			string strSelect = txtContent.SelectedText;
			int intIndexTmp = 0;
			int intStart = 0;
			int intEnd = 0;
			if (strSelect.Contains("▓"))
			{
				intIndexTmp = txtContent.SelectionStart;
				for (int i = intIndexTmp; intIndexTmp < txtContent.Text.Length; i++)
				{
					if (txtContent.Text.Substring(i, 1) == "▓")
					{
						intEnd = i;
						break;
					}
				}

				for (int i = intIndexTmp; intIndexTmp > 0; i--)
				{
					if ( i== 0)
					{
						intStart = 0;
						break;
					}
					if (txtContent.Text.Substring(i-1, 1) == "▓")
					{
						intStart = i + 2;
						break;
					}
					intStart = 0;
				}

				strSelect = txtContent.Text.Substring(intStart, intEnd - intStart);

				//int Tmp = intIndexTmp / 25;
				//if ((Tmp + 1) * 25 >= txtContent.Text.Length)
				//{
				//    strSelect = txtContent.Text.Substring(Tmp * 25);
				//    strSelect = strSelect.Replace("▓\r\n", "");
				//}
				//else
				//{
				//    strSelect = txtContent.Text.Substring(Tmp * 25, 22);
				//}
				
				// GetDataObject检索当前剪贴板上的数据
				Clipboard.SetDataObject(strSelect, true);
			}



			//if (strSelect == "▓")
			//{
			//    //int intIndex = txtContent.SelectionStart;
			//    if (intIndex < 22)
			//    {
			//        strSelect = txtContent.Text.Replace("▓","");
			//    }
			//    else
			//    {
			//        strSelect = txtContent.Text.Substring(intIndex - 22, 22);
			//    }
			//    //strSelect = strSelect.Replace("\r\n", "");
			//    string[] strArr = strSelect.Split(">".ToCharArray());
			//    if (strArr.Length > 1)
			//    {
			//        strSelect = strArr[strArr.Length - 1].Replace("\r\n", "");
			//        strSelect = ">" + strSelect;
			//    }
			//    else
			//    {
			//        strSelect = strSelect.Replace("\r\n", "");
			//    }
			//    // GetDataObject检索当前剪贴板上的数据
			//    Clipboard.SetDataObject(strSelect, true);
			//}
		}

		private void tbcCopy_Click(object sender, EventArgs e)
		{
			string strSelect = "";
			if (tbcCopy.SelectedIndex == 0)
			{
				strSelect = txtPhone.Text;
				// GetDataObject检索当前剪贴板上的数据
				Clipboard.SetDataObject(strSelect, true);
			}
			else
			{
				strSelect = txtPC.Text;
				// GetDataObject检索当前剪贴板上的数据
				Clipboard.SetDataObject(strSelect, true);
			}
		}

		private void tsmKeyRule_Click(object sender, EventArgs e)
		{
			ArrayList objArrayList = new ArrayList();

			if (dgwContent.SelectedRows.Count > 0)
			{
				for (int i = 0; i < dgwContent.SelectedRows.Count; i++)
				{
					EmailTempletEntity objEmailTempletEntity = (EmailTempletEntity)dgwContent.SelectedRows[i].Tag;
					objArrayList.Add(objEmailTempletEntity.ContentKeyID);
				}
			}

			if (objArrayList.Count > 0)
			{
				frmRule objfrmRule = new frmRule(objArrayList);
				objfrmRule.ShowDialog();
			}
		}

		private void ctmKey_Opening(object sender, CancelEventArgs e)
		{
			if (dgwContent.Rows.Count == 0)
			{
				if (dgwContent.SelectedRows.Count <= 0)
				{
					e.Cancel = true;
				}	
			}
		}

		public void btnReflash_Click(object sender, EventArgs e)
		{
			txtCreatePreson.Text = "";
			Innit();
		}

		private void dgwContent_SelectionChanged(object sender, EventArgs e)
		{
			if (dgwContent.SelectedRows.Count > 0)
			{
				if (dgwContent.SelectedRows[0].Tag == null)
				{
					return;
				}
				int selectIndex = dgwContent.SelectedRows[0].Index;
				DataGridViewCellEventArgs arg = new DataGridViewCellEventArgs(0, selectIndex);
				dgwContent_CellClick(null, arg);

			}
		}

		private void tvClass_KeyPress(object sender, KeyPressEventArgs e)
		{
		}

        #region Ext
        public void OpenEditForm()
        {
            this.btn_Ext_MailEdit.Enabled = true;
            this.btn_Ext_MailEdit_Click(null, null);
        }

        public void SendToMCS()
        {
            this.btn_Ext_MailEdit.Enabled = false;
            frmExtEdit.SendToMCS();
            
        }

	    private frm_Ext_Edit frmExtEdit = null;
	    private void btn_Ext_MailEdit_Click(object sender, EventArgs e)
        {
            if(frmExtEdit  != null
                && !frmExtEdit.IsDisposed)
            {
                this.TopLevel = false;
                frmExtEdit.TopLevel = true;
                frmExtEdit.type = tbcCopy.SelectedIndex;
                frmExtEdit.objEmailTempletEntity = this._emailTempletEntity;
                frmExtEdit.TemplateInit();
                return;
            }

            frmExtEdit = new frm_Ext_Edit(this);
            frmExtEdit.type = tbcCopy.SelectedIndex;
            frmExtEdit.objEmailTempletEntity = this._emailTempletEntity;

            frmExtEdit.Show();

	        frmExtEdit.TopLevel = true;
        }

        private void btn_Ext_MailContentDetails_Click(object sender, EventArgs e)
        {
            if (this._emailTempletEntity == null)
            {
                MessageBox.Show("Cann't get mail template info!");
                return;
            }
            frm_Ext_MailContentDetails _extMailContentDetails  = new frm_Ext_MailContentDetails();
            this.Hide();
            _extMailContentDetails.type = tbcCopy.SelectedIndex;
            _extMailContentDetails.objEmailTempletEntity = this._emailTempletEntity;
            _extMailContentDetails.ShowDialog();
            this.Show();
        }
        #endregion 

        private void btn_MailParagragh_Click(object sender, EventArgs e)
        {
            if (this._emailTempletEntity == null)
            {
                MessageBox.Show("Cann't get mail template info!");
                return;
            }
            frm_Ext_ParagraghCombine _frmExtParagraghCombine = new frm_Ext_ParagraghCombine();
            this.Hide();
            _frmExtParagraghCombine.type = tbcCopy.SelectedIndex;
            _frmExtParagraghCombine.objEmailTempletEntity = this._emailTempletEntity;
            _frmExtParagraghCombine.ShowDialog();
            this.Show();
        }

	    public string Get_txtContent()
	    {
	        return this.txtContent.Text;
	    }

        private void frmTemplateImportAndInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt && e.KeyCode == Keys.T)
            {
                if(this.btn_Ext_MailEdit.Enabled)
                    this.btn_Ext_MailEdit_Click(null,null);
                return;
            }
        }
	}
}